// 生成8位随机id
export const random8BitId = (): string => {
  return Math.random().toString(36).slice(-8)
}

/** 显示弹窗
 * @param {string} title 弹窗标题
 * @param {string} icon 弹窗图标
 * @param {string} duration 弹窗持续时间
 * @param {string} mask 是否显示透明蒙层，防止触摸穿透
 * @param {string} image 自定义图标的本地路径，image 的优先级高于 icon
 * @param {string} success 成功回调
 * @param {string} fail 失败回调
 * @param {string} complete 完成回调
 */
export const showToast = (
  title: string,
  icon: "none" | "success" | "loading" | "error" | undefined = 'none',
  duration = 1500,
  mask = false,
  image = '',
  success = () => { },
  fail = () => { },
  complete = () => { }
) => {
  uni.showToast({
    title: title,
    icon: icon,
    duration: duration,
    mask: mask,
    image: image,
    success: success,
    fail: fail,
    complete: complete
  });
}

/** 将canvas临时保存到本地，返回图片地址
 * 自定义组件实例
 * @param {Vue} component 自定义组件实例
 * @param {string} canvasId canvas的id
 * @param {string} fileType 文件类型，jpg或者png
 * @param {string} quality 图片质量，0-1
 * @param {string} complete 完成回调
 */
export const canvasToTempFilePath = (
  component: Vue,
  canvasId: string,
  fileType: "jpg" | "png" = 'jpg',
  quality: number = 1,
  complete: (res: any) => void,
) => {
  return new Promise((resolve, reject) => {
    uni.canvasToTempFilePath({
      canvasId: canvasId,
      fileType: fileType,
      quality: quality,
      success: (res: any) => {
        resolve(res.tempFilePath);
      },
      fail: (err: any) => {
        reject(err);
      },
      complete: complete
    }, component);
  })
}


/** 保存图片到系统相册
 * @param {string} filePath 图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
 * @param {string} complete 完成回调
 */
export const saveImageToPhotosAlbum = (
  filePath: string,
  complete: (res: any) => void,
) => {
  return new Promise((resolve, reject) => {
    uni.saveImageToPhotosAlbum({
      filePath: filePath,
      success: (res: any) => {
        resolve(res);
      },
      fail: (err: any) => {
        reject(err);
      },
      complete: complete
    });
  })
}


/** 开启分享功能 */
export const showShareMenu = () => {
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  });
}

/**
 * 遍历对象，将所有key为id的值替换为随机id
 * @param {object} obj 需要遍历的对象
 */
export const replaceId = (obj: any) => {
  for (let key in obj) {
    if (key === 'id') {
      obj[key] = random8BitId()
    } else if (typeof obj[key] === 'object') {
      replaceId(obj[key])
    }
  }
}
